<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\wxPay;
use fast\Random;
use think\Validate;

/**
 * 咨询师接口
 */
class Teacher extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $classList = [];
    protected $reply_ids = [];

    public function _initialize()
    {
        //分类
        $this->classList = model('\app\admin\model\allclass\Allclass')->getClassList();
    }

    /**
     * 咨询师列表
     *
     */
    public function index()
    {   
        $data = [];
        $keyword = $this->request->request('keyword');//关键词
        $classid = $this->request->request('classid');//分类ID
        $sex = $this->request->request('sex');//1男2女
        $minprice = $this->request->request('minprice');//价格区间小
        $maxprice = $this->request->request('maxprice');//价格区间大
        $grade = $this->request->request('grade');//资质
        
        $page = $this->request->request('page');//分页
        //$userid = $this->request->request('userid');//用户ID
        $pageNum  = 6;//每页个数

        $where = array();
        $where['t.status'] = 0;
        $where['t.is_live'] = 1;

        $w_keyword = [];
        if(!empty($keyword)){
            $w_keyword = ['t.name' => ['LIKE', "%{$keyword}%"]];
        }

        $w_classid = [];
        if(!empty($classid)){
            $w_classid = ['t.classid' => ['LIKE', "%{$classid},%"]];
        }

        if(!empty($sex)){
            $where['t.sex'] = $sex;
        }

        $w_grade = [];
        if(!empty($grade)){
            $w_grade = ['t.grade' => ['LIKE', "%{$grade},%"]];
        }

        //价格
        $price = [];
        if(!empty($minprice) && !empty($maxprice)){
            if(empty($maxprice)){
                $price = ['k.price' => ['>=', $minprice]];
            }else{
                $price = ['k.price' => ['between', [$minprice,$maxprice]]];
            }
        }

        /*$t_list = db('teacher')
        ->alias('t')
        ->join('task k','t.id = k.teacher_id')
        ->where($where)
        ->where($w_classid)
        ->where($w_grade)
        ->where($price)
        ->group('k.teacher_id')
        ->field('t.*,k.teacher_id,k.price')
        ->select();*/

        $start = ($page-1)*$pageNum;

        //查询总页数
        $count = db('teacher')
        ->alias('t')
        ->join('task k','t.id = k.teacher_id')
        ->where($where)
        ->where($w_keyword)
        ->where($w_classid)
        ->where($w_grade)
        ->where($price)
        ->group('k.teacher_id')
        ->field('t.*,k.teacher_id,k.price')
        ->count();

        $maxpages = ceil($count/$pageNum);
        if($page > $maxpages){
            $this->success('最后一页了',$data);
        }

        //咨询师列表
        $teacher_list = db('teacher')
        ->alias('t')
        ->join('task k','t.id = k.teacher_id')
        ->where($where)
        ->where($w_keyword)
        ->where($w_classid)
        ->where($w_grade)
        ->where($price)
        ->group('k.teacher_id')
        ->field('t.*,k.teacher_id,k.price')
        ->order('t.sort', 'desc')
        ->limit($start,$pageNum)
        ->select();

        if(!empty($teacher_list)){
            foreach($teacher_list as $key=>$value){

                $teacher_list[$key]['classid_title'] = model("\app\admin\model\allclass\Allclass")->getClassidInfo($value['classid']);//分类
                $teacher_list[$key]['headimg'] = getImagesUrl($value['headimg']);
                //咨询师任务最低价格
                $teacher_list[$key]['minprice'] = $this->getminprice($value['id']);
                //咨询数
                $teacher_list[$key]['services_num'] = 0;
                //好评率
                $teacher_list[$key]['praise'] = "0%";
              
            }
        }

        //分类列表
        $data = ['maxpages'=>$maxpages,'teacher_list'=>$teacher_list];
        $this->success('请求成功',$data);
    }

    //咨询师详情
    public function info(){

        $data = [];
        $userid = $this->request->request('userid');//用户ID
        $teacher_id = $this->request->request('teacher_id');//咨询师ID

        if(empty($userid)){
            $this->success('用户未登录',$data);
        }

        if(empty($teacher_id)){
            $this->success('查询数据错误',$data);
        }

        //查询咨询师数据
        $data = db('teacher')->where('id', $teacher_id)->find();

        //等级资质
        $grade_list = [];
        if(!empty($data['grade'])){
            $grade = array_filter(explode(',',$data['grade']));
            foreach($grade as $key=>$value){
                $grade_list[$key]['id'] = $value;
                $grade_list[$key]['name'] = db('grade')->where('id', $value)->value('grade_title');
            }
        }
        $data['grade_list'] = $grade_list;

        //证书
        $certificate_list = [];
        if(!empty($data['certificate'])){
            if(strstr($data['certificate'], ',')){
                $certificate = array_filter(explode(',',$data['certificate']));
                foreach($certificate as $key=>$value){
                    $certificate_list[$key]['url'] = getImagesUrl($value);
                }
            }else{
                $certificate_list[0]['url'] = getImagesUrl($data['certificate']);
            }
        }
        $data['certificate_list'] = $certificate_list;

        //封面图
        $data['cover'] = getImagesUrl($data['cover']);

        //用户评价
        $data['user_praise_num'] = "0";//评价数量
        $data['user_praise'] = "0";//1-5评级
        //咨询数
        $data['services_num'] = 0;
        //好评率
        $data['praise'] = "0%";
        //是否收藏
        $data['is_collect'] = $this->getTecollect($userid,$teacher_id);//0没收藏 1收藏过

        //咨询师任务列表
        $task = db('task')->where('teacher_id', $teacher_id)->where('status',0)->select();
        if(!empty($task)){
            foreach($task as $key=>$value){
                $task[$key]['classid_title'] =model("\app\admin\model\allclass\Allclass")->get_class_name($value['classid']);//分类
            }
        }

        $data['task'] = $task;
        $this->success('请求成功',$data);
    }

    /**
     * 咨询师预约服务
     */
    public function order(){

        $data = [];
        $userid = $this->request->request('userid');//用户ID
        $task_id = $this->request->request('task_id');//任务ID

        if(empty($userid)){
            $this->success('用户未登录',$data);
        }

        if(empty($task_id)){
            $this->success('数据错误',$data);
        }

        //查询任务数据
        $data = db('task')->where('id', $task_id)->find();

        //查询任务关联咨询师数据
        $teacher = db('teacher')->where('id', $data['teacher_id'])->find();

        $data['teacher_name'] = $teacher['name'];
        $data['classid_title'] = model("\app\admin\model\allclass\Allclass")->getClassidInfo($teacher['classid']);//分类
        $data['headimg'] = getImagesUrl($teacher['headimg']);

        $this->success('请求成功',$data);

    }
    

    /**
     * 确认订单
     */
    public function order_cron(){

        $data = [];
        $userid = $this->request->request('userid');//用户ID
        $task_id = $this->request->request('task_id');//任务ID
        $service_type = $this->request->request('service_type');//服务类型 text文字 voice语音 video视频 
        $nums = $this->request->request('nums');//任务数量

        if(empty($userid)){
            $this->success('用户未登录',$data);
        }
        if(empty($task_id)){
            $this->success('数据错误',$data);
        }
        //查询任务数据
        $data = db('task')->where('id', $task_id)->find();
        
        if(empty($data)){
            $this->success('查询任务不存在',$data);
        }

        //订单金额
        $order_amount = $nums*$data['price'];

        //创建订单
        $s_order_amount = [];
        $order_sn = getOrderSn();
        $s_order_amount['order_sn'] = $order_sn;//订单编号
        $s_order_amount['user_id'] = $userid;//用户ID
        $s_order_amount['order_amount'] = $order_amount;//订单金额
        //$s_order_amount['real_amount'] = $real_amount;//实付金额
        //$s_order_amount['discount_amount'] = $coupon_money;//优惠金额
        //$s_order_amount['coupon_id'] = $coupon_id;//优惠券ID
        $s_order_amount['type'] = "service";
        $s_order_amount['task_id'] = $task_id;//任务ID
        $s_order_amount['price'] = $data['price'];//任务单价
        $s_order_amount['unit_time'] = $data['unit_time'];//单位时长
        $s_order_amount['nums'] = $nums;//任务数量
        $s_order_amount['surplus_nums'] = $nums;//剩余次数
        $s_order_amount['service_type'] = $service_type;//服务类型 text文字 voice语音 video视频 
        $s_order_amount['pay_status'] = 0;//支付状态已完成
        $s_order_amount['createtime'] = time();//创建时间
        $s_order_amount['expirytime'] = time()+24*60*60;//过期时间延迟24小时
        $s_order_amount['pay_type'] = "wxpay";
    
        $order_id = db('task_order')->insertGetId($s_order_amount);

        $ret = [];
        if($order_id){
            $ret['error'] = 0;
            $ret['order_amount'] = $order_amount;
            $ret['order_id'] = $order_id;
            $ret['order_sn'] = $order_sn;
            $this->success('生成订单成功',$ret);
        }else{
            $ret['error'] = 1;
            $this->success('生成订单失败',$ret);
        }

    }


    /**
     * 支付订单
     */
    public function buy(){
        
        $order_id = $this->request->param('order_id');//order_id
        $order_sn = $this->request->param('order_sn');//order_sn
        $coupon_id = $this->request->param('coupon_id',0);//优惠券ID
        $user_id = $this->request->param('userid');//用户ID
        $order_amount = $this->request->param('order_amount');//订单金额
        //$real_amount = $this->request->param('real_amount');//实付金额
        $openid = $this->request->param('openid');//openid

        //$uid = $this->auth->id;
        //if($user_id != $uid){
           // $this->error('用户信息错误');
        //}

        $info = model("\app\admin\model\order\TaskOrder")->where('id',$order_id)->find();
        if(!$info){
            $this->error('订单不存在');
        }

        //验证优惠券是否有效
        $coupon_money = 0;//优惠金额
        if(!empty($coupon_id)){
            $coupon_money =  $this->getVerifyCoupon($coupon_id,$user_id);
        }

        //计算实付金额
        $real_amount = $order_amount-$coupon_money;
        if($real_amount < 0){
            $real_amount = 0;//优惠抵扣全部
            $coupon_money = $order_amount;//重置优惠金额为订单金额
        }else{
            //格式化价格
            $real_amount = number_format($real_amount, 2, '.', '');
        }

        //查询支付订单
        $order_info = model("\app\admin\model\order\TaskOrder")->get_task_order_info($info['task_id'],$user_id,$order_id);

        if(!empty($order_info['id'])){

            if($order_info['pay_status'] == 1){
                //支付完成
                $msg = "此订单已支付，请前往个人中心咨询服务";
                $this->success($msg);

            }else{

                //直接购买成功
                if($real_amount == 0){

                    $s_order_amount = [];
                    //$s_order_amount['order_amount'] = $order_amount;//订单金额
                    $s_order_amount['real_amount'] = $real_amount;//实付金额
                    $s_order_amount['discount_amount'] = $coupon_money;//优惠金额
                    $s_order_amount['coupon_id'] = $coupon_id;//优惠券ID

                    $s_order_amount['pay_status'] = 1;//支付状态已完成
                    $s_order_amount['expirytime'] = time();//过期时间
                    $s_order_amount['updatetime'] = time();//修改时间
                    
                    //修改订单信息
                    $upd = db('task_order')->where('id', $order_info['id'])->update($s_order_amount);
                    if($upd){
                        //更新优惠券状态
                        if(!empty($coupon_id)){
                           $this->updatecoupon($coupon_id,$order_info['id']); 
                        }
                        $msg = "购买成功，请前往个人中心咨询服务";
                        $this->success($msg);
                    }

                }else{

                    //重新开启订单 有效期重置24小时
                    $s_order_amount = [];
                    //$s_order_amount['order_amount'] = $order_amount;//订单金额
                    $s_order_amount['real_amount'] = $real_amount;//实付金额
                    $s_order_amount['discount_amount'] = $coupon_money;//优惠金额
                    $s_order_amount['coupon_id'] = $coupon_id;//优惠券ID

                    $s_order_amount['pay_status'] = 0;//支付状态已完成
                    //$s_order_amount['createtime'] = time();//创建时间
                    $s_order_amount['expirytime'] = time()+24*60*60;//过期时间延迟24小时
                    $s_order_amount['pay_type'] = "wxpay";
                    $s_order_amount['updatetime'] = time();//修改时间
                    
                    //修改订单信息
                    $upd = db('task_order')->where('id', $order_info['id'])->update($s_order_amount);
                    if($upd){
                       
                        //查询paylog记录
                        $pay_log = db('pay_log')->where('order_sn',$order_info['order_sn'])->find();

                        if(empty($pay_log['id'])){

                            //添加paylog
                            $pay_log = [];
                            $pay_log['user_id'] = $user_id;
                            $pay_log['order_sn'] = $order_sn;
                            $pay_log['type'] = "service";
                            $pay_log['money'] = $real_amount;
                            $pay_log['createtime'] = time();//创建时间

                            $log_id = db('pay_log')->insertGetId($pay_log);

                        }else{

                            //更新支付数据
                            $new_pay_log = [];
                            $new_pay_log['money'] = $real_amount;
                            $new_pay_log['updatetime'] = time();//修改时间
                            db('pay_log')->where('id', $pay_log['id'])->update($new_pay_log);
                            $log_id = $pay_log['id'];
                        }

                        //调用支付类 发起支付
                        $total_fee = $real_amount*100;//已分为单位
                        $out_trade_no = "S".date("YmdHis")."-".$log_id;//订单标号
                        //$openid = "oNjbJ5M-dE3KbVo9mtnSXkmGRvBc";
                        $wxPay = new wxPay();
                        $return = $wxPay->getPay($total_fee,$out_trade_no,'JSAPI',$openid,'服务咨询');

                        /*
                        echo "<pre>";
                        print_r($return);
                        die;*/
                        $this->success("创建订单成功",$return);

                    }else{
                        $this->error('订单生成失败');
                    }

                }

            }

        }else{

            $this->error('未查到订单信息');
        }

    }


    /**
     * 验证优惠券是否有效
     */
    public function getVerifyCoupon($coupon_id = 0, $user_id = 0){

        $coupon_money = 0;//优惠金额

        if(empty($coupon_id) || empty($user_id)){
            return $coupon_money;
        }

        //查询是否可用优惠券
        $coupon = db('coupon_list')->where('id',$coupon_id)->where('user_id',$user_id)->where('status',0)->find();
        if(!empty($coupon['id'])){
           
            //判断优惠券是否可以使用
            $new_time = time();
            if(($coupon['start_time'] <= $new_time) &&  ($new_time <= $coupon['end_time'])){
                return $coupon['money'];
            }else{
                return $coupon_money;
            }

        }else{
            return $coupon_money;
        }

    }


    /**
     * 更新优惠券状态
     * 
     */
    public function updatecoupon($coupon_id = 0, $order_id = 0){

        if(empty($coupon_id)){
            return false;
        }

        //修改信息
        $ret = db('coupon_list')->where('id', $coupon_id)->update(['type' => 'service','order_id' => $order_id,'use_time' => time(),'status' => 1]);

        if($ret){
            return true;
        }else{
            return false;
        }

    }


    //获取咨询师资质列表
    public function grade()
    {   
        $list = [];
        $list = model('\app\admin\model\grade\Grade')->getGradeList();
        $this->success('成功',$list);
    }


    /**
     * 收藏或取消收藏
     */
    public function getCollect(){

        $teacher_id = $this->request->request('teacher_id');//咨询师ID
        $userid = $this->request->request('userid');//用户ID

        //是否收藏
        $collect = db('teacher_collect')->where('user_id', $userid)->where('teacher_id', $teacher_id)->count();
        if($collect > 0){
            //取消收藏
            db('teacher_collect')->where('user_id', $userid)->where('teacher_id', $teacher_id)->delete();
            $msg = "取消成功";
        }else{
            //添加收藏
            $data = ['user_id' => $userid, 'teacher_id' => $teacher_id, 'createtime' => time()];
            db('teacher_collect')->insert($data);
            $msg = "收藏成功";
        }

        $this->success($msg,$collect);

    }

    /**
     * 判断咨询师是否被收藏
     */

    public function getTecollect($userid = "", $teacher_id = 0){
        
        $is_collect = 0;//收藏

        if(empty($userid) || empty($teacher_id)){
            return $is_collect;
        }

        //收藏
        $collect = db('teacher_collect')->where('user_id', $userid)->where('teacher_id', $teacher_id)->count();
        if($collect > 0){
            $is_collect = 1;
        }
        
        return $is_collect;
    }

    /**
    * 获取咨询师任务最低价格 
    */
    public function getminprice($teacher_id = ""){
        
        $ret = 0;
        $count = db('task')->where("teacher_id",$teacher_id)->count();
        if($count > 0){
            $ret = db('task')->where("teacher_id",$teacher_id)->min('price');
        }
        return $ret;
    }

}
